package com.chinaunicom.controller;

import com.chinaunicom.entity.LocalServiceInstance;
import com.chinaunicom.entity.ResponseResult;
import com.chinaunicom.service.TestService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: ruiyanglee
 * @date: 2020-09-22 14:00
 * @description:
 */

@RestController
@RequestMapping("/")
// 配置文件变化时自动拉取
@RefreshScope
public class TestController {

    @Autowired
    public TestService testService;

    @Autowired
    public DiscoveryClient discoveryClient;

    @Value("pay-service")
    public String payService;

    @Value(value = "${config.info}")
    private String configInfo;

    @GetMapping
    public ResponseResult getMsg() {
        return testService.getMsg();
    }

    @GetMapping("/instance")
    public ResponseResult getInstance() {
        // 对ServiceInstance进行本地封装
        List<LocalServiceInstance> result = new ArrayList<LocalServiceInstance>();

        // 通过服务名称获取 ServiceInstance， 可以在order-client端实现，获取可使用的服务实例
        List<ServiceInstance> list = discoveryClient.getInstances(payService);
        if (list != null && list.size() > 0) {
            for (ServiceInstance instance : list) {
                LocalServiceInstance localServiceInstance = new LocalServiceInstance();
                BeanUtils.copyProperties(instance, localServiceInstance);
                result.add(localServiceInstance);
            }
        }
        return ResponseResult.ok().flag(true).data(result).message("请求成功");
    }

    @GetMapping("/services")
    public ResponseResult getServers() {
        // 获取所有services
        List<String> services = discoveryClient.getServices();
        return ResponseResult.ok().flag(true).message("请求成功").data(services);
    }

    @GetMapping("/port")
    public ResponseResult getPort() {
        return testService.getPort();
    }

    @GetMapping("/circuitBreak/{id}")
    public ResponseResult paymentCircuitBreaker(@PathVariable("id") Integer id) {
        return testService.paymentCircuitBreaker(id);
    }

    @GetMapping("/configInfo")
    public ResponseResult getConfigInfo() {
        return ResponseResult.ok().data(configInfo);
    }
}
